<?php

namespace Modules\H5\Http\Controllers\Book;

use Modules\Common\Models\Ebooks;
use Modules\Common\Models\EbookChapters;
use Modules\Common\Models\EbookSections;
use Modules\Common\Models\Categories;
use Modules\Common\Models\Bookshelf;
use Modules\Common\Models\Orders;
use Modules\Common\Models\Members;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;

class Book
{
    /**
     * 获取书本完整的详情
     * @Route(path=/api/h5/book-details)
     */
    public function bookDetails()
    {
        $bookId = request('book_id');
        $userId = auth('web')->user()->id; // 获取当前认证的用户ID

        // 获取书籍详情
        $ebookDetails = Ebooks::with(['category', 'bookshelf', 'orders'])
            ->where('id', $bookId)
            ->where('is_published',1)
            ->first();

        if (!$ebookDetails) {
            return Api::fail('书籍不存在', 404);
        }

        // 检查是否加入书架
        $isInBookshelf = Bookshelf::where('ebook_id', $bookId)
                                   ->where('user_id', $userId)
                                   ->exists();
        // 检查是否购买
        $isPurchased = Orders::where('ebook_id', $bookId)
                              ->where('user_id', $userId)
                              ->where('status',2)
                              ->exists();

        // 检查是否是会员
        $isMember = Members::where('user_id', $userId)
                               ->where('status', 1)
                               ->exists();

        // 将这些状态添加到返回的数据中
        $ebookDetails->is_in_bookshelf = $isInBookshelf;
        $ebookDetails->is_purchased = $isPurchased;
        $ebookDetails->is_member = $isMember;

        return Api::success($ebookDetails);
    }
    
    /**
     * 获取书本介绍
     * @Route(path=/api/h5/book-description)
     */
    public function bookDescription()
    {
        $bookId = request('book_id');
        $ebookDescription = Ebooks::where('id', $bookId)->where('is_published',1)->get(['description']);
        return Api::success($ebookDescription);
    }
    
    /**
     * 获取书本完整目录
     * @Route(path=/api/h5/book-catalog)
     */
    public function bookCatalog()
    {
        $bookId = request('book_id');
        // 预加载每个章节的节
        $ebookChapters = EbookChapters::with('sections')->where('ebook_id', $bookId)->get();
        
        // 遍历每个章节和节，替换换行符为<br/>
        foreach ($ebookChapters as $chapter) {
            foreach ($chapter->sections as $section) {
                // 假设section内容存储在content属性中
                $section->content = str_replace("\n", "<br/>", $section->content);
            }
        }
        
        // 返回完整的目录结构
        return Api::success($ebookChapters);
    }
    
    /**
     * 获取分类
     * @Route(path=/api/category)
     */
    public function Category()
    {
        $eid = request('eid');
        $categories = Categories::where('is_enabled',1)->where('eid',$eid)->get();
    
        return Api::success($categories);
    }
    
    
    /**
     * 根据分类和是否免费查询电子书
     * @Route(path=/api/h5/search-ebooks)
     */
    public function searchEbooks()
    {
        $categoryId = request('category_id'); // 获取分类参数
        $isFree = request('is_free'); // 获取是否免费的参数
        $bookName = request('book_name');
        $eid = auth('web')->user()->eid;

        // 构建查询
        $query = Ebooks::with(['category']);

        // 如果提供了是否免费的参数，则应用该过滤条件
        if ($categoryId !== null) {
            $query->where('category_id', $categoryId);
        }

        if ($isFree !== null) {
            $query->where('is_free', $isFree);
        }

        if ($bookName !== null) {
            $query->where('book_name','like', '%' . $bookName . '%');
        }

        // 执行查询
        $query->orderByRaw('id desc , created_at desc');
        $ebooks = $query->where('is_published',1)->where('eid',$eid)->paginate(request('per_page', 15));

        // 返回查询结果
        return Api::success($ebooks);
    }
    
    
     /**
     * 会员精选书籍
     * @Route(path="/api/h5/cherry-pick-books")
     */
    public function cherryPickBooks()
    {
        $eid = auth('web')->user()->eid;
        $query = Ebooks::where('available', '<>', 1)->where('is_free',2)->with(['category']);
        $data = $query->where('is_published',1)->where('eid',$eid)->orderBy('created_at', 'desc')->paginate(request('per_page', 15));
        return Api::success($data);
    }
    
}